<?php

/**
 * Options Class aka "options maker framework"
 *  
 * @author Santiago Dimattia <master@teleportz.com.ar>
 * @version dev 
 */
class Options {
	
	/**
	 * Option name
	 */
	public $option_name = '';
	
	/**
	 * Array of options
	 */	
	public $options = array();
	
	/**
	 * Array of sections
	 */
	public $sections = array();

	/**
	 * Set configs.
	 *
	 */
	function __construct($dbname)
	{
		$this->option_name = $dbname;
	}
	
	/**
     * Generate form tables
	 * 
	 * @return string Generated form fields
	 */
	public function prepare()
	{
		$data = '';
		
		foreach($this->sections as $key => $info)
		{
			$data .= '<fieldset style="border: 1px solid #999; padding: 0 20px 20px 20px; margin-bottom: 20px;">';
			$data .= '<legend style="padding: 0 10px; color: #006ad5; text-transform: uppercase;"><strong>' . $info['name'] . '</strong></legend>';

			$data .= '<p style="font-weight: bold;">' . $info['description'] . '</p>';
			
			$data.= '<table class="form-table">';
			
			foreach($this->options[$info['id']] as $option)
			{
				$data .= $this->_render($option);
			}
			
			$data .= '</table></fieldset>';
		}
		
		return $data;
	}
	
	/**
	 * Render table. Calls function to render based on field type,
	 * 
	 * @param array $vars Options info
	 * @return string $data Generated form field
	 */
	private function _render($vars)
	{
        // Open tr
        $data = '<tr valign="top">';
		$data .= '<th scope="row"><label for="' . $vars['id'] . '">' . $vars['name'] . '</label></th>';
		
		$data .= '<td>';
		
        // Generate field
		switch($vars['type'])
		{
			case 'text':
				$data .= $this->_render_text($vars);
			break;
			
			case 'textarea':
				$data .= $this->_render_textarea($vars);
				$data .= '<br />';
			break;
			
			case 'checkbox':
				$data .= $this->_render_checkbox($vars);
			break;
			
			case 'select':
				$data .= $this->_render_select($vars);
			break;
			
		}
		
        // Close tr
		$data .= '<span style="display: block; font-size: 10px;">' . $vars['description'] . '</span>';
		$data .= '</td>';
		$data .= '</tr>';
		
		return $data;
	}
	
	/**
	 * Render text input
	 * 
	 * @param array $vars Option info
	 * @return string $data Generated field
	 */
	private function _render_text($vars)
	{
		$data = '<input type="text" name="' . $vars['id'] . '" id="' . $vars['id'] . '" value="' . $vars['value'] . '" />';
		
		return $data;
	}
	
	/**
	 * Render textarea
	 * 
	 * @param array $vars Option info
	 * @return string $data Generated field
	 */
	private function _render_textarea($vars)
	{
		$data = '<textarea name="' . $vars['id'] . '" id="' . $vars['id'] . '">' . $vars['value'] . '</textarea>';
		
		return $data;
	}
	
	/**
	 * Render checkbox
	 * 
	 * @param array $vars Option info
	 * @return string $data Generated field
	 */
	private function _render_checkbox($vars)
	{
		$data = '<input type="checkbox" name="' . $vars['id'] . '" id="' . $vars['id'] . '" ';
		
		if($vars['value'] == 'on')
		{
			$data .= 'checked="checked"';
		}
		
		$data .= ' />';
		
		return $data;
	}

	/**
	 * Render select input
	 * 
	 * @param array $vars Option info
	 * @return string $data Generated field
	 */
	private function _render_select($vars)
	{
		$data = '<select name="' . $vars['id'] . '" id="' . $vars['id'] . '">';
		
		foreach($vars['options'] as $key => $val)
		{
			$data .= '<option value="' . $key . '"';
			
			if($key == $vars['value'])
			{
				$data .= ' selected="selected" ';
			}
			
			$data .= '>' . $val . '</option>';
		}
		
		$data .= '</select>';
		
		return $data;
	}

	
	/**
	 * Validate fields
	 * 
	 * @param array $vars Option info
	 * @param mixed $post Value to validate
	 * @return
	 */
	private function _validate($vars, $post)
	{
		// Validate checkbox's (Only accept "on" or "off")
		if(isset($vars['type']) && $vars['type'] == 'checkbox')
		{
			if($post != 'on')
			{
				return 'off';
			}
			
			return $post;
		}

		// If $vars['validate'] is an array, search for whitelisted values (if found, return $post)
		if(isset($vars['validate']) && is_array($vars['validate']))
		{
			foreach($vars['validate'] as $key)
			{
				if($key == $post)
				{
					return $post;
				}
			}
			
			if(!empty($vars['default']))
			{
				$vars['default'] = '';
			}
			
			return $vars['default'];
		}

		// If value is required and $post is empty, set default value
		if(isset($vars['required']) && $vars['required'] == 'required' && empty($post))
		{
			return $vars['default'];
		}
		
		// If $post is empty, set a blank value		
		if(empty($post))
		{
			return '';
		}
		
		// If $vars['validate'] is a valid function, use it	
		if(!empty($vars['validate']) && function_exists($vars['validate']))
		{
			return $vars['validate']($post);
		}
		
		// If value is not required, and dosn't require validation, return $post
        return $post;
	}

	/**
	 * Check if we need to update options
	 * 
	 * @return bool
	 */
	public function check_update()
	{
		if((isset($_GET['page']) && isset($_POST['save'])) && ($_GET['page'] == 'fazio' && $_POST['save'] == 'true'))
		{
			$this->update();
			return true;
		}
		
		return false;
	}
	
	/**
	 * Update db options
	 * 
	 * @param string $option_name the name of the option saved in db
	 * @return bool
	 */
	public function update()
	{
		$update = array();
		
		foreach($this->options as $key => $val)
		{
			foreach($val as $key => $val)
			{
				$id = $val['id'];
				$option = (isset($_POST[$id]) ? $_POST[$id] : '');
				
				$newval = $this->_validate($val, $option);
				
				$update[$id] = $newval;
			}
		}

		// update option
		update_option($this->option_name, $update);
		
		// Redirect
		header("Location: themes.php?page=fazio&saved=true");
		die();
	}
}